﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NavLine.Aircraft
{
	public partial class AC_Controller
	{
		public bool TowardLine = false;
		Line3G _targetline;
		Line3G TargetLine
		{
			get
			{
				return _targetline;
			}
			set
			{
				_targetline = value;
				LineHdg = value.Heading;
			}
		}
		double EndDist;
		double TurnDist = 5000;
		public V3G LineReference;
		double LineHdg = double.NaN;

		public event ACControllerEvent OnLineEnd;
		void ProcessLine(double dt)
		{
			if (TowardLine)
			{
				TowardPoint = true;

				V3G tgt = _targetline.NearestPoint(aircraft.position);
				if (!tgt.Valid)
					tgt = _targetline.B;
				double dist = aircraft.position.GetDist(tgt);
				dist = Math.Max(0, TurnDist - dist);
				TargetPoint = tgt.AddLocal(dist, tgt.GetHeading(_targetline.B));
				LineReference = TargetPoint;
				if (_targetline.B.GetDist(aircraft.position) < EndDist)
				{
					MaintainHeading(_targetline.B.GetHeading(_targetline.A) + 180);
					if (OnLineEnd != null)
						OnLineEnd(this);
				}
			}
			else
				LineReference = V3G.Null;
		}

		public void NavigateLine(Line3G iline, double enddist)
		{
			ResetControl();
			EndDist = enddist;
			TargetLine = iline;
			TowardLine = true;
		}
	}
}